import matplotlib.pyplot as plt
import numpy as np

from DHTOA1 import process_traffic_scenario, calculate_path_delays, calculate_total_delay, \
    semi_calculate_static_latency, load_traffic_data
from find_min_max_delay_path import optimize_reconfiguration
from topo1 import build_hybrid_topology_shared_tor


def calculate_routing_delays(topology, traffic_data):
    """计算并收集三种路由策略的延迟数据"""
    results = {
        'time' :[],
        'traffic': [],
        'static_delay': [],
        'semi_static_delay': [],
        'hybrid_delay': []
    }

    # 遍历所有流量场景
    for i, scenario in enumerate(traffic_data.values()):
        print(scenario)
        # 获取当前流量的时间戳
        # timestamp = scenario['timestamp']
        # 计算当前流量总需求
        current_matrix = scenario['matrix']
        total_traffic = np.sum(current_matrix)  # 计算矩阵所有元素之和作为总流量

        # 处理当前场景
        current_paths, current_traffic = process_traffic_scenario(
            topology,
            current_matrix,
            {
                'tor_nodes': {"ToR1", "ToR2", "ToR3", "ToR4"},
                'os_nodes': {"os1", "os2", "os3", "os4"},
                'threshold': 40
            }
        )

        # 静态路由延迟（直接使用当前路径）
        static_delays = calculate_path_delays(current_paths, current_traffic, topology)
        static_max = max(static_delays.values()) if static_delays else 0

        # 光电混合延迟（需要重构优化）
        if i == 0:
            # 第一个场景没有前序状态
            hybrid_max = static_max
        else:
            # 获取前一个场景路径
            prev_scenario = list(traffic_data.values())[i - 1]
            prev_paths, _ = process_traffic_scenario(
                topology,
                prev_scenario['matrix'],
                {
                    'tor_nodes': {"ToR1", "ToR2", "ToR3", "ToR4"},
                    'os_nodes': {"os1", "os2", "os3", "os4"},
                    'threshold': 40
                }
            )
            # 执行重构优化
            recon_paths, recon_delays, static_delays = optimize_reconfiguration(
                current_traffic, topology, prev_paths, current_paths
            )
            hybrid_max = calculate_total_delay(
                current_paths, recon_paths, static_delays, recon_delays,
                current_traffic,optical_reconstruction_delay=1, optical_capacity=200, verbose=True
            )

            # 半静态路由延迟（取静态和重构的较大值）
            # semi_max = semi_calculate_static_latency(
            #     current_paths, recon_paths if i > 0 else {},
            #     static_delays if i > 0 else {}, recon_delays if i > 0 else {},
            #     current_traffic, optical_capacity=200,verbose=True)
            # # ) if i > 0 else static_max
            semi_max = semi_calculate_static_latency(current_paths, recon_paths, static_delays, recon_delays,
                                                    current_traffic, optical_capacity=200, verbose=True)

            # 记录结果
            # results['time'].append(timestamp)
            results['traffic'].append(total_traffic)
            results['static_delay'].append(static_max)
            results['semi_static_delay'].append(semi_max)
            results['hybrid_delay'].append(hybrid_max)

    return results


def visualize_delay_comparison(results):
    """可视化时延对比"""
    plt.figure(figsize=(10, 6))

    # 排序数据点
    sorted_indices = np.argsort(results['traffic'])
    traffic = np.array(results['traffic'])[sorted_indices]
    static = np.array(results['static_delay'])[sorted_indices]
    semi = np.array(results['semi_static_delay'])[sorted_indices]
    hybrid = np.array(results['hybrid_delay'])[sorted_indices]

    # 绘制曲线
    plt.plot(traffic, static, 'g--', label='Static Routing')
    plt.plot(traffic, semi, 'b-', label='Semi-Static Routing')
    plt.plot(traffic, hybrid, 'r-', label='Hybrid Optimization')

    # 图表装饰
    plt.title('all_to_all+base Network Latency Comparison')
    plt.xlabel('Total Traffic (Gbps)')
    plt.ylabel('Maximum Latency (ms)')
    plt.grid(True, linestyle='--', alpha=0.6)
    plt.legend()
    plt.tight_layout()

    # 保存并显示
    plt.savefig('latency_comparison.png')
    plt.show()


# ------------------ 修改后的主程序 -------------------
if __name__ == "__main__":
    # 初始化网络拓扑
    # G = build_hybrid_topology_shared_tor(num_tor=4)
    G = build_hybrid_topology_shared_tor(num_tor=16)
    # 加载所有流量场景（不再限制特定时间戳）
    # traffic_data = load_traffic_data('traffic_simulation.json', traffic_type="all_to_all+base")
    traffic_data = load_traffic_data('traffic_simulation.json', traffic_type="all_to_all+base")

    # 计算各场景时延
    delay_results = calculate_routing_delays(G, traffic_data)
    print("=========================输出各种时延===========================")
    # 输出各种时延
    print("\n时延结果:")
    for i, (traffic, static, semi, hybrid) in enumerate(zip(
            # delay_results['time'],
            delay_results['traffic'],
            delay_results['static_delay'],
            delay_results['semi_static_delay'],
            delay_results['hybrid_delay']
    )):
        # print(f"时间戳: {time}")
        print(f"场景 {i + 1}:")
        print(f"流量: {traffic:.2f} Gbps")
        # print(f"静态路由时延: {static:.2f} ms")
        print(f"半静态路由时延: {semi:.2f} ms")
        # print(f"混合路由时延: {semi:.2f} ms")
        print(f"混合路由时间差: {hybrid - static:.2f} ms")

    print("=========================输出各种时延===========================")
    # 可视化结果
    visualize_delay_comparison(delay_results)

    # 输出统计信息
    print("\n性能对比统计:")
    print(f"平均时延 - 静态路由: {np.mean(delay_results['static_delay']):.2f}ms")
    print(f"平均时延 - 半静态路由: {np.mean(delay_results['semi_static_delay']):.2f}ms")
    print(f"平均时延 - 光电优化: {np.mean(delay_results['hybrid_delay']):.2f}ms")